package com.menghao.rpc.serialize.hessian;

import com.caucho.hessian.io.SerializerFactory;
import com.menghao.rpc.serialize.Serializer;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * <p>Hessian序列化类.<br>
 *
 * @author MarvelCode.
 */
public class HessianSerializer implements Serializer {

    private static final String CONTENT_TYPE = "hessian";

    static final SerializerFactory SERIALIZER_FACTORY = new SerializerFactory() {
        @Override
        public ClassLoader getClassLoader() {
            return Thread.currentThread().getContextClassLoader();
        }
    };

    @Override
    public String contentType() {
        return CONTENT_TYPE;
    }

    @Override
    public void serialize(OutputStream out, Object object) throws IOException {
        HessianObjectOutput hessianObjectOutput = new HessianObjectOutput(out);
        hessianObjectOutput.writeObject(object);
        hessianObjectOutput.flush();
    }

    @Override
    public Object deserialize(InputStream in) throws IOException {
        HessianObjectInput hessianObjectInput = new HessianObjectInput(in);
        return hessianObjectInput.readObject();
    }

    @Override
    public Object deserialize(InputStream in, Class<?> clazz) throws IOException {
        HessianObjectInput hessianObjectInput = new HessianObjectInput(in);
        return hessianObjectInput.readObject(clazz);
    }
}
